package com.chouxiaozi.wechatpublic.service.wechat.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chouxiaozi.wechatpublic.entity.WechatCustomMenu;
import com.chouxiaozi.wechatpublic.mapper.WechatCustomMenuMapper;
import com.chouxiaozi.wechatpublic.service.wechat.IWechatCustomMenuService;
import com.chouxiaozi.wechatpublic.vo.WechatCustomMenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 微信公众号菜单 服务实现类
 * </p>
 *
 * @author ws
 * @since 2019-12-31
 */
@Service
public class WechatCustomMenuServiceImpl extends ServiceImpl<WechatCustomMenuMapper, WechatCustomMenu> implements IWechatCustomMenuService {

    @Override
    public List<WechatCustomMenuVo> getMenuByGroupCode(String groupCode) {
        //List<WechatCustomMenuVo> list=(List<WechatCustomMenuVo>)redisUtil.hget(CoreConsts.WECHAT_GROUP_CUSTOM_MENU, groupCode);
        List<WechatCustomMenuVo> list = new ArrayList<>();
        if (list==null||list.isEmpty()) {
            QueryWrapper<WechatCustomMenu> queryWrapper = new QueryWrapper();
            queryWrapper.eq("delete_state",0).eq("group_code",groupCode)
                    .isNull("parent_id").orderByAsc("menu_order");

            List<WechatCustomMenu> menus = list(queryWrapper);
            list=new ArrayList<>();
            for (Iterator iterator = menus.iterator(); iterator.hasNext();) {
                WechatCustomMenu wechatCustomMenu = (WechatCustomMenu) iterator.next();
                WechatCustomMenuVo menuVo=new WechatCustomMenuVo();
                BeanUtils.copyProperties(wechatCustomMenu, menuVo);
                //查询下级菜单
                queryWrapper = new QueryWrapper();
                queryWrapper.eq("delete_state",0).eq("group_code",groupCode)
                        .eq("parent_id",menuVo.getId()).orderByAsc("menu_order");

                List<WechatCustomMenu> subMenus = list(queryWrapper);
                List<WechatCustomMenuVo> subMenuVos=new ArrayList<>();
                for (Iterator iterator2 = subMenus.iterator(); iterator2.hasNext();) {
                    WechatCustomMenu wechatCustomMenu2 = (WechatCustomMenu) iterator2.next();
                    WechatCustomMenuVo subMenuVo=new WechatCustomMenuVo();
                    BeanUtils.copyProperties(wechatCustomMenu2, subMenuVo);
                    subMenuVos.add(subMenuVo);
                }

                if (subMenuVos!=null||!subMenuVos.isEmpty()) {
                    menuVo.setChList(subMenuVos);
                }
                list.add(menuVo);
            }

            /*if (list!=null&&!list.isEmpty()) {
                redisUtil.hset(CoreConsts.WECHAT_GROUP_CUSTOM_MENU, groupCode, list);
            }*/

        }
        return list;
    }
}
